#region using directives

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using Assergs.Windows;
using Bookvar.ApplicationModel;
using Bookvar.Collaboration;
using Bookvar.Common;
using Bookvar.ObjectModel;
using Bookvar.ServiceModel;
using Bookvar.UI;
using Bookvar.UI.Arrangers;
using BookvarWpf.Windows;
using BookvarWpf.Windows.Collaboration;
using ButtonBase=System.Windows.Controls.Primitives.ButtonBase;
using ComboBox=System.Windows.Controls.ComboBox;
using LocalizationResources = Bookvar.UI.Localization.Resources;
using MessageBox=System.Windows.MessageBox;

#endregion

namespace BookvarWpf
{
	public partial class MainPage
	{
		private static void ShowModalDialog( ToolWindow window )
		{
			window.StartPosition = ToolWindowStartPosition.CenterParent;
			window.ShowModalDialog();
		}

		private static void ShowDialogCentered( ToolWindow window )
		{
			window.StartPosition = ToolWindowStartPosition.CenterParent;
			window.Parent = ToolWindow.ModalContainerPanel;
			window.Show();
		}

		private static void ShowDialog( ToolWindow window )
		{
			window.Parent = ToolWindow.ModalContainerPanel;
			window.Show();
		}

		private void ShowAttachmentsCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			Topic topic = e.Parameter as Topic;
			if ( topic == null )
			{
				topic = mindMapPanel.SelectedTopic ?? mindMapPanel.MainTopic;
			}
			addAttachmentsWindow = new AddAttachmentsWindow( topic, currentMap );
			ShowModalDialog( addAttachmentsWindow );
		}

		private void ShowNotesCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			Topic topic = e.Parameter as Topic;
			if ( topic == null )
			{
				topic = mindMapPanel.SelectedTopic ?? mindMapPanel.MainTopic;
			}
			AddNotesWindow window = new AddNotesWindow( topic );
			ShowModalDialog( window );
		}

		private void ShowHyperlinkCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			Topic topic = e.Parameter as Topic;
			if ( topic == null )
			{
				topic = mindMapPanel.SelectedTopic ?? mindMapPanel.MainTopic;
			}
			AddHyperlinkWindow window = new AddHyperlinkWindow( topic );
			ShowModalDialog( window );
		}

		private static void CreateNewMapCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			MainPage page = (MainPage) sender;
			MainTopic mainTopic = new MainTopic();
			mainTopic.Name = "Main Topic";
			//mainTopic.SubTopics.Add( new Topic() );

			//page.fileName = string.Empty;
			MindMap map = new MindMap( mainTopic );

			page.AddMindMap( map );
		}

		private static void OpenMapCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			var page = (MainPage) sender;

			var fileDialog = new OpenFileDialog();
			fileDialog.Filter = "Bookvar MindMap (*.bmm)|*.bmm";

			if ( fileDialog.ShowDialog() == DialogResult.OK )
			{
				string fileName = fileDialog.FileName;
			    mindmapService.OpenMindmapFromDisk( fileName );
			}

			page.UpdateTitle();
		}

		private static void SaveMapCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			var page = (MainPage) sender;
			bool isSavedOk = true;
			if ( String.IsNullOrEmpty( page.currentMap.FileName ) || page.currentMap.FileName == MindMap.MindmapDefaultFileName )
			{
				string fileName = String.Empty;
				var fileDialog = new SaveFileDialog();
				fileDialog.Filter = "Bookvar MindMap (*.bmm)|*.bmm";

				if ( fileDialog.ShowDialog() == DialogResult.OK )
				{
					fileName = fileDialog.FileName;
					PersistenceService.RegisterMindmapForPersistence( page.currentMap, fileName );
					isSavedOk = PersistenceService.SaveMapToPersistence( page.currentMap );
					RecentFiles.AddFileToRecent( fileName );
				}
			}
			else
			{
				isSavedOk = PersistenceService.SaveMapToPersistence( page.currentMap );
			}
			if ( !isSavedOk )
			{
				MessageBox.Show( LocalizationResources.ErrorSavingMindmap,
				                 LocalizationResources.ErrorDefaultCaption,
				                 MessageBoxButton.OK,
				                 MessageBoxImage.Exclamation );
			}
			else
			{
				AutoSaveRecoveryService.ResetMapAutoSave( page.currentMap );
			}
		}

		private static void SaveAsMapCommandExecuted( object sender, ExecutedRoutedEventArgs e )
		{
			MainPage page = (MainPage) sender;
			bool isSavedOk = true;

			SaveFileDialog fileDialog = new SaveFileDialog();
			fileDialog.Filter = "Bookvar MindMap (*.bmm)|*.bmm";

			if ( fileDialog.ShowDialog() == DialogResult.OK )
			{
				string fileName = fileDialog.FileName;
				PersistenceService.RegisterMindmapForPersistence( page.currentMap, fileName );
				isSavedOk = PersistenceService.SaveMapToPersistence( page.currentMap );
				RecentFiles.AddFileToRecent( fileName );
			}

			if ( !isSavedOk )
			{
				MessageBox.Show( LocalizationResources.ErrorSavingMindmap,
				                 LocalizationResources.ErrorDefaultCaption,
				                 MessageBoxButton.OK,
				                 MessageBoxImage.Exclamation );
			}
			else
			{
				AutoSaveRecoveryService.ResetMapAutoSave( page.currentMap );
			}
		}

		private void OnStartDatePickerValueChanged( object sender, RoutedPropertyChangedEventArgs<DateTime?> e )
		{
			if ( e.NewValue.HasValue && mindMapPanel.SelectedTopic != null )
			{
				CustomProperty timelineStartDate;
				Topic topic = mindMapPanel.SelectedTopic;
				if (
					!topic.CustomProperties.TryGetItem( TimelineTopicArranger.TimelineStartDateKey,
					                                    out timelineStartDate ) )
				{
					timelineStartDate = new CustomProperty( TimelineTopicArranger.TimelineStartDateKey );
					topic.CustomProperties.Add( timelineStartDate );
				}
				if ( timelineStartDate.Value != (object) startDatePicker.Value )
				{
					timelineStartDate.Value = startDatePicker.Value;
				}
			}
		}

		private void OnEndDatePickerValueChanged( object sender, RoutedPropertyChangedEventArgs<DateTime?> e )
		{
			if ( e.NewValue.HasValue && mindMapPanel.SelectedTopic != null )
			{
				CustomProperty timelineEndDate;
				Topic topic = mindMapPanel.SelectedTopic;
				if ( !topic.CustomProperties.TryGetItem( TimelineTopicArranger.TimelineEndDateKey, out timelineEndDate ) )
				{
					timelineEndDate = new CustomProperty( TimelineTopicArranger.TimelineEndDateKey );
					topic.CustomProperties.Add( timelineEndDate );
				}
				if ( timelineEndDate.Value != (object) endDatePicker.Value )
				{
					timelineEndDate.Value = endDatePicker.Value;
				}
			}
		}

		private void btnSearchImages_Click( object sender, RoutedEventArgs e )
		{
			LiveImagesWindow window = new LiveImagesWindow();
			ShowDialogCentered( window );
		}

		private void btnBug_Click( object sender, RoutedEventArgs e )
		{
			SubmitBugWindow window = new SubmitBugWindow();
			ShowModalDialog( window );
		}

		private void btnPublishMap_Click( object sender, RoutedEventArgs e )
		{
			if ( String.IsNullOrEmpty( currentMap.FileName ) || currentMap.FileName == MindMap.MindmapDefaultFileName )
			{
				MessageBox.Show( LocalizationResources.ErrorSaveMapBeforePublish,
				                 LocalizationResources.AlertDefaultCaption,
				                 MessageBoxButton.OK,
				                 MessageBoxImage.Exclamation );
			}
			else
			{
				PublishMap window = new PublishMap( currentMap.FullPath );
				ShowModalDialog( window );
			}
		}

		private void btnConsole_Click( object sender, RoutedEventArgs e )
		{
			ConsoleWindow window = new ConsoleWindow();
			window.ConsoleControl.MindMapPanel = mindMapPanel;
			ShowModalDialog( window );
		}

		private void OnAddImageClick( object sender, RoutedEventArgs e )
		{
			OpenFileDialog fileDialog = new OpenFileDialog();
			fileDialog.Filter = "Images (*.jpg, *.png, *.bmp, *.gif)|*.jpg;*.png;*.bmp;*.gif";
			fileDialog.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyPictures );

			if ( fileDialog.ShowDialog() == DialogResult.OK )
			{
				( (ButtonBase) sender ).CommandParameter = fileDialog.FileName;

				//TODO: is this needed
				mindMapPanel.InvalidateTopicsArrange();
			}
		}

		private void OnAddMovieClick( object sender, RoutedEventArgs e )
		{
			//byte[] fileBytes = null;

			OpenFileDialog fileDialog = new OpenFileDialog();
			fileDialog.Filter = "Windows Media Video (*.wmv)|*.wmv";
			fileDialog.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Personal );

			if ( fileDialog.ShowDialog() == DialogResult.OK )
			{
				( (ButtonBase) sender ).CommandParameter = fileDialog.FileName;

				//TODO: this will be a problem
				//resource.ItemSource = new Uri(tempFile);

				//TODO: is this needed
				mindMapPanel.InvalidateTopicsArrange();
			}
		}

		private void OnOptionsClicked( object sender, RoutedEventArgs args )
		{
			OptionsWindow window = new OptionsWindow();
			ShowModalDialog( window );
		}

		private void btnStartServer_Click( object sender, RoutedEventArgs e )
		{
			StartCollaborationServer();
		}

		private void btnStopServer_Click( object sender, RoutedEventArgs e )
		{
			try
			{
				presenter.StopCollaborationServer();
			}
			catch ( CollaborationException ex )
			{
				Logger.Log( ex.Message );
			}
		}

		private void btnConnectToServer_Click( object sender, RoutedEventArgs e )
		{
			if ( presenter.CollaborationMode == CollaborationMode.Normal )
			{
				ConnectToServer window = new ConnectToServer();
				window.ConnectClicked += ConnectToServerConnectEvent;
				ShowModalDialog( window );
			}
		}

		private void btnDisconnectFromServer_Click( object sender, RoutedEventArgs e )
		{
			if ( presenter.CollaborationMode == CollaborationMode.Client )
			{
				presenter.StopCollaborationClient();
			}
		}

		private void btnPresentation_Click( object sender, RoutedEventArgs args )
		{
			var presentation = new Presentation();

			presentation.Mindmap = mindMapPanel.Mindmap;
			presentation.Skin = mindMapPanel.Skin;

			NavigationService.Navigate( presentation );
		}

		private void ComboSelectionChanged( object sender, SelectionChangedEventArgs e )
		{
			ComboBoxItem arranger = ( (ComboBoxItem) combo.SelectedItem );
			if ( arranger == mindmapLayoutComboBoxItem )
			{
				mindMapPanel.TopicConnector = new BezierTopicConnector();
				mindMapPanel.TopicArranger = new MindmapTopicArranger( mindMapPanel );
			}
			else if ( arranger == balancedLayoutComboBoxItem )
			{
				mindMapPanel.TopicConnector = new BezierTopicConnector();
				mindMapPanel.TopicArranger = new MindmapTopicArranger( mindMapPanel );
				mindMapPanel.TopicArranger.BalanceMap();
			}
			else if ( arranger == timelineLayoutComboBoxItem )
			{
				mindMapPanel.TopicConnector = new EmptyTopicConnector();
				mindMapPanel.TopicArranger = new TimelineTopicArranger( mindMapPanel );
			}
			else if ( arranger == normalLayoutComboBoxItem )
			{
				mindMapPanel.TopicConnector = new EmptyTopicConnector();
				mindMapPanel.TopicArranger = new NormalTopicArranger( mindMapPanel );
			}
			else
			{
				Debug.Fail( "Unexpected arranger." );
			}
		}

		private void SkinSelectionChanged( object sender, SelectionChangedEventArgs e )
		{
			string skin = ( (ComboBoxItem) ( (ComboBox) e.Source ).SelectedItem ).DataContext.ToString();
			mindMapPanel.Skin = new Uri( skin, UriKind.Absolute);
		}

		private void OnUpdateCheckClicked( object sender, RoutedEventArgs e )
		{
			IUpdateService updateService = BookvarApplication.Current.ServiceLayer.GetService<IUpdateService>();
			if ( updateService != null )
			{
				updateService.StartCheckForUpdates();
			}
		}
	}
}